#include "WCSSend.h"
#include <QEventLoop>
#include <QTimer>
#include <QDateTime>
#include "systemconfiguration.h"
#include "../../HttpServer/httpsend.h"
#include "component_log.h"


WCSSend::WCSSend(QObject* parent)
	: ComponentBase(parent)
{
	m_errmsg = "";
	m_name = "WCS消息发送组件";
	m_type = Component::component_wcsSend;
	m_taskId = QDateTime::currentDateTime().toString("MMddhhmm");
}

WCSSend::~WCSSend()
{}

structJ(WCSAns,
	mapping(QString, msg);
mapping(int, code);
prop(&code, &msg);
)

//任务完成
bool WCSSend::SendTaskFinishInfo(const QByteArray& data, QString& errmsg)
{
	QByteArray ans;
	bool ret = SendToWCS("/task/finishInfo", data, ans);
	if (!ret) {
		errmsg = ans;
		log_error("Send task finish info failed");
		return false;
	} else {
		WCSAns ansData = {};
		ansData.fromJson(ans);
		if (ansData.code() < 0) {
			errmsg = ansData.msg();
			log_error("Send task finish info failed, ans = {}", ans);
			return false;
		}
	}

	if (m_subscribers.contains(WCSendType::wcs_send_taskfinish)) {
		for (auto iter : m_subscribers[WCSendType::wcs_send_taskfinish]) {
			iter(data);
		}
	}

	return true;
}


// 订阅接口，提供给其它组件订阅本组件消息的接口
bool WCSSend::RegisterSubscriberFunction(int type, Callback callback)
{
	if (type < 1 || type >(int)WCSendType::wcs_send_max) {
		log_error("RegisterSubscriberFunction type [{}] error", type);
		return false;
	}
	WCSendType mType = (WCSendType)type;
	auto iter = m_subscribers.find(mType);
	if (iter == m_subscribers.end()) {
		QVector<std::function<int(const QByteArray&)>> temp;
		temp.append(callback);
		m_subscribers.insert(mType, temp);
	} else {
		iter.value().append(callback);
	}
	return true;
}



// 组件初始化处理函数
int WCSSend::ComponentInit()
{
	//if (systemcfg->GetDebugMode() == 1) {
	//	m_host = "http://127.0.0.1:8089/api/v1/wcs/";
	//	log_trace("wcs send init for debug successed");
	//	return true;
	//}

	auto cfg = syscfg->GetWcsCfg();
	if (cfg.wcsIP.isEmpty()) {
		SetErrmsg(u8"配置的IP为空");
		return -99;
	}
	if (cfg.wcsport < 1) {
		SetErrmsg(u8"配置的端口号异常");
		return -99;
	}

	m_host = "http://" + cfg.wcsIP + ":" + QString::number(cfg.wcsport);

	m_send = new HttpSend(this);

	log_trace("wcs send init uccessed， host = {}", m_host);
	return 0;
}
/*自检接口*/
bool WCSSend::ComponentCheckSelfState()
{
	return true;
}
/*复位接口*/
bool WCSSend::ComponentSelfReset()
{
	return true;
}

void TimeDelay(int s)
{
	QEventLoop loop;
	QTimer::singleShot(s * 1000, &loop, &QEventLoop::quit);
	loop.exec();
}

bool WCSSend::SendToWCS(const QString& cmdpath, const QByteArray& data, QByteArray& ans)
{
	int ret = m_send->SendPostMsgByHttp(m_host + cmdpath, data, ans);
	if (ret == send_ok) {
		return true;
	} else if (ret == send_param_error) {
		log_error("param error: path ={}", m_host + cmdpath);
		ans = "参数错误";
		return false;
	} else if (ret == send_timeout) {
		int ret = HttpResend(m_host + cmdpath, data, ans, 5);	// 重复发送5次
		if (ret == send_ok) {
			return true;
		} else {
			ans = "连续发送5次均发送超时，请手动重试";
			return false;
		}
	} else {
		log_error("send http failed, ret = {}", ret);
		ans = "发送异常";
		return false;
	}
}

int WCSSend::HttpResend(const QString& path, const QByteArray& data, QByteArray& ans, int times)
{
	for (int i = 0; i < times; i++) {
		TimeDelay(10);
		int ret = m_send->SendPostMsgByHttp(path, data, ans);
		if (ret != send_timeout) {
			return ret;
		}
	}
	log_error("send time out for 5 times");
	return send_timeout;
}
